import { readFileSync } from 'fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import packages from '../../package.json' with { type: 'json' };

const __dirname = fileURLToPath(dirname(import.meta.url));

const soucePackageJson = () => {
    const reserved = [
        'name',
        'version',
        'main',
        'types',
        'repository',
        'author',
        'keywords',
        'publishConfig',
        'license',
        'exports'
    ];
    return JSON.stringify(
        Object.keys(packages).reduce((pre, next) => {
            if (reserved.includes(next)) pre[next] = packages[next];
            else pre;
            return pre;
        }, {}),
        null,
        4
    );
};

export default function () {
    return {
        name: 'copy-release-file',
        generateBundle() {
            this.emitFile({
                type: 'asset',
                fileName: 'README.md',
                source: readFileSync(resolve(__dirname, '../../README.md'))
            });
            this.emitFile({
                type: 'asset',
                fileName: 'package.json',
                source: soucePackageJson()
            });
        }
    };
}
